/**
 * Configuration management module
 * Handles loading, validation, and merging of config options
 */

export const DEFAULT_CONFIG = {
  cron: '0 8 * * *',          // 8 AM daily
  multiple: false,            // Single window
  delay: 0,                   // No delay
  browser: null               // System default
};

/**
 * Validate cron expression format
 * @param {string} cronExpr - Cron expression
 * @returns {boolean} Is valid
 */
function isValidCron(cronExpr) {
  // Basic cron validation: 5 parts (minute hour day month dayOfWeek)
  const parts = cronExpr.trim().split(/\s+/);
  if (parts.length !== 5) return false;
  
  // Each part should be number, *, or range
  return parts.every(part => /^(\*|\d+(-\d+)?|\d+(,\d+)*)$/.test(part));
}

/**
 * Validate configuration object
 * @param {Object} config - Configuration to validate
 * @returns {{isValid: boolean, errors: string[]}} Validation result
 */
export function validateConfig(config) {
  const errors = [];
  
  // Required: URL
  if (!config.url) {
    errors.push('URL is required');
  } else {
    try {
      new URL(config.url);
    } catch {
      errors.push(`Invalid URL: ${config.url}`);
    }
  }
  
  // Required: cron expression
  if (!config.cron) {
    errors.push('Cron expression is required');
  } else if (!isValidCron(config.cron)) {
    errors.push(`Invalid cron expression: ${config.cron}`);
  }
  
  // Optional: delay should be positive number
  if (config.delay !== undefined && config.delay < 0) {
    errors.push('Delay must be non-negative');
  }
  
  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * Load and merge configuration with defaults
 * @param {Object} userConfig - User-provided configuration
 * @returns {Object} Merged configuration
 */
export function loadConfig(userConfig = {}) {
  return {
    ...DEFAULT_CONFIG,
    ...userConfig
  };
}

/**
 * Load configuration from file
 * @param {string} configPath - Path to config file
 * @returns {Promise<Object>} Configuration object
 */
export async function loadConfigFromFile(configPath) {
  try {
    const { default: config } = await import(configPath);
    return loadConfig(config);
  } catch (error) {
    throw new Error(`Failed to load config from ${configPath}: ${error.message}`);
  }
}